package com.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.springboot.common.Result;
import com.springboot.entity.UserAddress;
import com.springboot.mapper.UserAddressMapper;
import com.springboot.service.IUserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.utils.IntegerUtils;
import com.springboot.utils.JwtTokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 收货地址表 服务实现类
 *
 * @author zjb
 * @since 2025-10-22
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements IUserAddressService {

    /**
     * 取消用户默认地址设置
     *
     * @param userId 用户ID
     */
    private void setDefaultAddressNon(Integer userId) {
        UpdateWrapper<UserAddress> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId).set("is_default", 0);
        update(updateWrapper);
    }

    /**
     * 添加收货地址
     *
     * @param userAddress 收货地址信息
     * @return 添加结果
     */
    @Override
    public Result addAddress(UserAddress userAddress) {
        if (!StringUtils.hasText(userAddress.getConsignee())) {
            return Result.error("收货人姓名不能为空");
        }
        if (!StringUtils.hasText(userAddress.getPhone())) {
            return Result.error("收货人电话不能为空");
        }
        if (!StringUtils.hasText(userAddress.getProvince())) {
            return Result.error("省份不能为空");
        }
        if (!StringUtils.hasText(userAddress.getCity())) {
            return Result.error("城市不能为空");
        }
        if (!StringUtils.hasText(userAddress.getDistrict())) {
            return Result.error("区县不能为空");
        }
        if (!StringUtils.hasText(userAddress.getDetailAddress())) {
            return Result.error("详细地址不能为空");
        }

        if (IntegerUtils.isNull(userAddress.getUserId())) {
            userAddress.setAddressId(JwtTokenUtils.getCurrentUser().getUserId());
        } else if (!Objects.equals(userAddress.getUserId(), JwtTokenUtils.getCurrentUser().getUserId())) {
            return Result.error("只能给自己添加地址");
        }

        //如果没设置默认值，则为0
        if (IntegerUtils.isNull(userAddress.getIsDefault())) {
            userAddress.setAddressId(0);

            //如果设为默认，则取消其他地址默认值
        } else if (userAddress.getIsDefault() == 1) {
            setDefaultAddressNon(userAddress.getUserId());
        }

        if (save(userAddress)) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }

    }

    /**
     * 删除收货地址
     *
     * @param addressId 地址ID
     * @return 删除结果
     */
    @Override
    public Result removeAddress(Integer addressId) {
        if (IntegerUtils.isNull(addressId)) {
            return Result.error("地址id不能为空");
        }
        UserAddress address = getById(addressId);
        if (!Objects.equals(address.getUserId(), JwtTokenUtils.getCurrentUser().getUserId())) {
            return Result.error("只能删除自己的收货地址");
        }
        if (removeById(addressId)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 更新收货地址
     *
     * @param addressId   地址ID
     * @param userAddress 收货地址信息
     * @return 更新结果
     */
    @Override
    public Result updateAddress(Integer addressId,UserAddress userAddress) {
        if (IntegerUtils.isEmptyOrZero(addressId)) {
            return Result.error("地址id为空或非法值");
        }
        if (!Objects.equals(addressId, JwtTokenUtils.getCurrentUser().getUserId())) {
            return Result.error("地址信息与当前用户关系有误");
        }
        userAddress.setAddressId(addressId);
        UserAddress oldUserAddress = getById(addressId);
        if (oldUserAddress==null){
            return Result.error("没有此地址信息");
        }
        // 检查是否有任何字段被修改
        boolean isChanged = !Objects.equals(userAddress.getConsignee(), oldUserAddress.getConsignee()) ||
                !Objects.equals(userAddress.getPhone(), oldUserAddress.getPhone()) ||
                !Objects.equals(userAddress.getProvince(), oldUserAddress.getProvince()) ||
                !Objects.equals(userAddress.getCity(), oldUserAddress.getCity()) ||
                !Objects.equals(userAddress.getDistrict(), oldUserAddress.getDistrict()) ||
                !Objects.equals(userAddress.getDetailAddress(), oldUserAddress.getDetailAddress()) ||
                !Objects.equals(userAddress.getPostalCode(), oldUserAddress.getPostalCode());
        
        // 如果没有任何字段被修改，则返回错误
        if (!isChanged) {
            return Result.error("你没有修改任何值");
        }
        
        // 检查是否已存在相同的地址信息
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getUserId, userAddress.getUserId())
                .ne(UserAddress::getAddressId, userAddress.getAddressId())
                .eq(UserAddress::getConsignee, userAddress.getConsignee())
                .eq(UserAddress::getPhone, userAddress.getPhone())
                .eq(UserAddress::getProvince, userAddress.getProvince())
                .eq(UserAddress::getCity, userAddress.getCity())
                .eq(UserAddress::getDistrict, userAddress.getDistrict())
                .eq(UserAddress::getDetailAddress, userAddress.getDetailAddress())
                .eq(UserAddress::getPostalCode, userAddress.getPostalCode());
        
        if (getOne(lambdaQueryWrapper) != null) {
            return Result.error("你已有相同的收货地址信息");
        }

        if (userAddress.getIsDefault() == 1) {
            setDefaultAddressNon(userAddress.getUserId());
        }
        if (updateById(userAddress)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 获取用户收货地址列表
     *
     * @param userId 用户ID
     * @return 地址列表
     */
    @Override
    public Result getAddress(Integer userId) {
        if (IntegerUtils.isEmptyOrZero(userId)) {
            return Result.error("用户id为空或非法值");
        }
        if (!Objects.equals(userId, JwtTokenUtils.getCurrentUser().getUserId())) {
            return Result.error("只能查看自己的地址信息");
        }
        LambdaQueryWrapper<UserAddress> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAddress::getUserId, userId);
        List<UserAddress> userAddress = list(lambdaQueryWrapper);
        if (userAddress != null) {
            return Result.success(userAddress, "获取成功");
        } else {
            return Result.error("没有收货地址");
        }
    }
}